﻿using System;
using System.Reflection;

namespace TestUp.Models
{
    public class EntitiesConverter
    {
        public static TShortEntity ToShortEntity<TShortEntity, TEntity>(TEntity entity)
            where TShortEntity : class, new()
        {
            var result = new TShortEntity();
            try
            {
                Type shortType = typeof(TShortEntity);
                Type entityType = typeof(TEntity);
                var properties =
                    shortType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                foreach (var shortProperty in properties)
                {
                    bool isVirtual = shortProperty.GetGetMethod().IsVirtual;
                    if (isVirtual)
                        continue;

                    var entityProperty = entityType.GetProperty(shortProperty.Name);
                    if (entityProperty != null)
                        shortProperty.SetValue(result, entityProperty.GetValue(entity, null), null);
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            return result;
        }

        public static TEntity ToEntity<TEntity, TShortEntity>(TShortEntity shortEntity) where TEntity : class, new()
        {
            var result = new TEntity();
            try
            {
                Type shortType = typeof(TShortEntity);
                Type entityType = typeof(TEntity);
                var properties =
                    shortType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                foreach (var shortProperty in properties)
                {
                    bool isVirtual = shortProperty.GetGetMethod().IsVirtual;
                    if (isVirtual)
                        continue;

                    var entityProperty = entityType.GetProperty(shortProperty.Name);
                    if (entityProperty != null)
                        entityProperty.SetValue(result, shortProperty.GetValue(shortEntity, null), null);
                }
            }
            catch (Exception)
            {
                return null;
            }

            return result;
        }
    }
}